package com.tianji.remark.service.impl;

import com.tianji.common.utils.UserContext;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.remark.service.ILikedStatService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author taohongrun
 * @since 2025-02-07
 */
//@Service
@RequiredArgsConstructor
public class LikedRecordServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {
    private final ILikedStatService statService;

    @Override
    @Transactional
    public void likeOrUnlike(LikeRecordFormDTO formDTO) {
        // 1.获取登录用户
        Long userId = UserContext.getUser();
        // 2.点赞或取消点赞
        boolean success = formDTO.getLiked() ? like(formDTO, userId) : unlike(formDTO, userId);
        if (!success) {
            return;
        }
        // 3.更新点赞数量
        statService.updateLikedTimes(formDTO);
    }

    @Override
    public Set<Long> isBizLiked(List<Long> bizIds) {
        Long userId = UserContext.getUser();
        // 2.查询点赞状态
        List<LikedRecord> list = lambdaQuery()
                .in(LikedRecord::getBizId, bizIds)
                .eq(LikedRecord::getUserId, userId)
                .list();
        // 3.返回结果
        return list.stream().map(LikedRecord::getBizId).collect(Collectors.toSet());
    }

    private boolean unlike(LikeRecordFormDTO formDTO, Long userId) {
        return lambdaUpdate()
                        .eq(LikedRecord::getUserId, userId)
                        .eq(LikedRecord::getBizId, formDTO.getBizId())
                        .remove()
        ;
    }

    private boolean like(LikeRecordFormDTO formDTO, Long userId) {
        // 1.查询
        Long count = lambdaQuery()
                .eq(LikedRecord::getUserId, userId)
                .eq(LikedRecord::getBizId, formDTO.getBizId())
                .count();
        if (count > 0) {
            // 已点赞，无需处理
            return false;
        }
        // 2.新增
        LikedRecord r = new LikedRecord();
        r.setUserId(userId);
        r.setBizId(formDTO.getBizId());
        r.setBizType(formDTO.getBizType());
        r.setCreateTime(LocalDateTime.now());
        r.setUpdateTime(LocalDateTime.now());
        return save(r);
    }

    @Override
    public void readLikedTimesAndSendMessage(String bizType, int maxBizSize) {

    }
}
